package com.project.modules.redEnvelope.utils;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 拆红包的算法工具类
 */
@Slf4j
public class RedEnvelopeUtil {


    /**
     * 拆红包的算法：在剩余红包平均值的 50% - 150% 浮动
     *
     * @param totalMoney        总金额
     * @param redEnvelopeNumber 红包数
     * @return 红包分配情况，从大到小排列
     */
    public static BigDecimal[] splitRedEnvelopeAlgorithm(BigDecimal totalMoney, int redEnvelopeNumber) {
        BigDecimal[] res = new BigDecimal[redEnvelopeNumber];
        BigDecimal useMoney = BigDecimal.ZERO;
        for (int i = 0; i < redEnvelopeNumber; i++) {
            if (i == redEnvelopeNumber - 1) {
                res[i] = totalMoney.subtract(useMoney);
            } else {
                BigDecimal avgMoney = totalMoney.subtract(useMoney)
                        .divide(BigDecimal.valueOf(redEnvelopeNumber - i), 2, RoundingMode.HALF_UP)
                        .divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP);
                // 在剩余红包平均值的 50% - 150% 浮动
                res[i] = RandomUtil.randomBigDecimal(avgMoney, avgMoney.multiply(BigDecimal.valueOf(3)))
                        .setScale(2, RoundingMode.HALF_UP);
            }
            useMoney = useMoney.add(res[i]);
        }
        Arrays.sort(res, (a, b) -> b.compareTo(a));
        return res;
    }

    public static String bigDecimals2String(BigDecimal[] bigDecimals) {
        StringBuilder stringBuilder = new StringBuilder();
        for (BigDecimal bd : bigDecimals) {
            stringBuilder.append(bd.toString()).append(", ");
        }

        // 删除末尾的逗号和空格
        if (stringBuilder.length() > 2) {
            stringBuilder.setLength(stringBuilder.length() - 2);
        }
        return stringBuilder.toString();
    }

    public static BigDecimal[] string2BigDecimals(String input) {
        if (input == null || input.isEmpty()) {
            return new BigDecimal[0]; // 返回一个空的BigDecimal数组
        }

        String[] parts = input.split(", ");
        BigDecimal[] bigDecimals = new BigDecimal[parts.length];
        for (int i = 0; i < parts.length; i++) {
            bigDecimals[i] = new BigDecimal(parts[i]);
        }
        return bigDecimals;
    }

    public static Map<Long, Integer> transferUserScore(Map<Object, Object> originalMap) {
        // 创建一个新的Map<Long, Integer>用于存储转换后的结果
        Map<Long, Integer> resultMap = new HashMap<>();

        // 遍历原始Map，并进行类型转换
        for (Map.Entry<Object, Object> entry : originalMap.entrySet()) {
            try {
                // 尝试将键和值转换为Long和Integer
                Long key = Long.parseLong(entry.getKey().toString());
                Integer value = Integer.parseInt(entry.getValue().toString());

                // 存储到新的Map中
                resultMap.put(key, value);
            } catch (NumberFormatException e) {
                // 处理类型转换异常，如果无法转换则忽略该键值对或采取其他适当的处理
                log.warn("转换异常，跳过：" + entry);
            }
        }
        return resultMap;
    }

    public static Map<Long, BigDecimal> transferUserMoney(Map<Object, Object> originalMap) {
        // 创建一个新的Map<Long, Integer>用于存储转换后的结果
        Map<Long, BigDecimal> resultMap = new HashMap<>();

        // 遍历原始Map，并进行类型转换
        for (Map.Entry<Object, Object> entry : originalMap.entrySet()) {
            try {
                // 尝试将键和值转换为Long和Integer
                Long key = Long.valueOf(entry.getKey().toString());
                BigDecimal value = new BigDecimal(entry.getValue().toString());

                // 存储到新的Map中
                resultMap.put(key, value);
            } catch (RuntimeException e) {
                // 处理类型转换异常，如果无法转换则忽略该键值对或采取其他适当的处理
                log.warn("转换异常，跳过：" + entry);
            }
        }
        return resultMap;
    }
}
